"""
@breif Let RaspberryPi speak out its ip address when started
@description
    - idea comes from https://shumeipai.nxez.com/2019/05/29/make-the-raspberry-pi-speak-its-own-ip-address.html
    - the way to get ip comes from https://www.jb51.net/article/173931.htm
    
@programer(copier) Stone at BlueNet, GDOU
@date Nov. 2020
"""
import socket
from os import path

import pygame as pyg


pyg.mixer.init()


# making directory and load sound
DIR_SND = path.dirname(__file__)  # directory of script file
DIR_SND = path.join(DIR_SND, '..', '..', 'resources', 'audio_speak_ip')
DIR_SND = path.abspath(DIR_SND)


def load_sound(path_dir):
    sounds = {}
    for i in range(10):
        pth = path.join(path_dir, '%i.wav'%i)
        sounds[str(i)] = pyg.mixer.Sound(pth)
        
    sounds['.'] = pyg.mixer.Sound(path.join(path_dir, 'dot.wav'))
    sounds['wrong'] = pyg.mixer.Sound(path.join(path_dir, 'go_wrong.wav'))
    
    return sounds


def get_host_ip():
    """comes from https://www.jb51.net/article/173931.htm"""
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip


def speak_ip(ip, sounds, duration=500):
    for c in ip:
        sounds[c].play()
        pyg.time.delay(duration)
    

if __name__ == '__main__':
    print(get_host_ip())
    sounds = load_sound(DIR_SND)
    
    my_ip =  get_host_ip()
    for i in range(100):
        try:
            speak_ip(my_ip, sounds)
            pyg.time.delay(2000)
        except:
            sounds['wrong'].play()
            pyg.time.delay(2000)
